using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.Material.ProductMaterial;
using ProduceBasicData.Domain.Inventories;
using ProduceBasicData.Domain.Material;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.Material.ProductMaterial
{
    /// <summary>
    /// 产品物料修改处理类
    /// </summary>
    public class UpdateProductMaterialHandler : IRequestHandler<UpdateProductMaterialCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<ProductMaterialModel> productMaterialRepository;
        private readonly IBaseRespository<GroupTypeDictionary> groupTypeRepository;
        private readonly IBaseRespository<CraftModel> craftRepository;
        private readonly IMapper mapper;

        public UpdateProductMaterialHandler(
            IBaseRespository<ProductMaterialModel> productMaterialRepository,
            IBaseRespository<GroupTypeDictionary> groupTypeRepository,
            IBaseRespository<CraftModel> craftRepository,
            IMapper mapper)
        {
            this.productMaterialRepository = productMaterialRepository;
            this.groupTypeRepository = groupTypeRepository;
            this.craftRepository = craftRepository;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(UpdateProductMaterialCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                // 根据ID获取产品物料数据
                var productMaterial = await productMaterialRepository.GetModelAsync(request.Id);
                if (productMaterial == null)
                {
                    result.Code = ApiEnum.Failed;
                    result.Msg = "产品物料不存在";
                    return result;
                }

                // 如果指定了群组类型ID，验证其是否存在
                if (request.GroupTypeId.HasValue)
                {
                    var groupType = await groupTypeRepository.GetModelAsync(request.GroupTypeId.Value);
                    if (groupType == null)
                    {
                        result.Code = ApiEnum.Failed;
                        result.Msg = "群组类型不存在";
                        return result;
                    }
                    productMaterial.GroupType = groupType.GroupTypeName;
                }

                // 如果指定了默认工艺路线ID，验证其是否存在
                if (request.DefaultCraftId.HasValue)
                {
                    var craft = await craftRepository.GetModelAsync(request.DefaultCraftId.Value);
                    if (craft == null)
                    {
                        result.Code = ApiEnum.Failed;
                        result.Msg = "默认工艺路线不存在";
                        return result;
                    }
                    productMaterial.DefaultCraftName = craft.CraftName;
                }

                // 将请求数据映射到现有产品物料对象（更新操作）
                mapper.Map(request, productMaterial);

                // 设置修改时间和修改人
                productMaterial.UpdateTime = DateTime.Now;
                if (!string.IsNullOrEmpty(request.UpdateName))
                {
                    productMaterial.UpdateName = request.UpdateName;
                }

                // 更新数据库
                await productMaterialRepository.Update(productMaterial);

                result.Code = ApiEnum.Success;
                result.Msg = "产品物料修改成功";
                result.Data = productMaterial.Id;
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"产品物料修改异常：{ex.Message}";
            }

            return result;
        }
    }
}
